package com.jdz.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.jdz.common.Const;
import com.jdz.common.ServerResponse;
import com.jdz.dao.*;
import com.jdz.pojo.*;
import com.jdz.service.IRaceTypeService;
import com.jdz.service.IUserService;
import com.jdz.util.DateTimeUtil;
import com.jdz.util.ExportExcel;
import com.jdz.util.MD5Util;
import com.jdz.util.SendMsgUtil;
import com.jdz.vo.ExcelFileVo;
import com.jdz.vo.ExportExcelVo;
import com.jdz.vo.ListUserVo;
import com.jdz.vo.UserVo;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
//import java.util.UUID;

/**
 * Created by sun
 **/
@Transactional
@Service("IUserService")
public class UserServiceImpl implements IUserService {


    private Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

    @Autowired
    UserMapper userMapper;
    @Autowired
    GroupMapper groupMapper;
    @Autowired
    GroupUserMapper groupUserMapper;

    @Autowired
    IRaceTypeService iRaceTypeService;

    @Autowired
    GroupPrivilegeMapper groupPrivilegeMapper;
    @Autowired
    PrivilegeMapper privilegeMapper;
    @Autowired
    ProjectDetailsMapper projectDetailsMapper;
    @Autowired
    ProjectDetailsUserMapper projectDetailsUserMapper;

    @Override
    public ServerResponse login(String stuid, String stupassword) {

        if(StringUtils.isBlank(stuid)){
            return ServerResponse.createByErrorMessage("学号不能为空");
        }
        if(StringUtils.isBlank(stupassword)){
            return ServerResponse.createByErrorMessage("密码不能为空");
        }

        User result = userMapper.checkStuId(stuid);

        if (result == null){
            return ServerResponse.createByErrorMessage("学号不存在");
        }
        if(result.getStatus()==1){
            return ServerResponse.createByErrorMessage("用户已被管理员封锁，请联系管理员");
        }

//如果不是今天重置
//        if(result.getLockTimes()!="5"&&!DateTimeUtil.isNow(result.getCreattime())){//如果不是今天，且没封锁初始化为0
//            User stu = new User();
//            stu.setStuno(result.getStuno());
//            stu.setLockTimes("0");
//            stu.setCreattime(new Date());
//            userMapper.updateByPrimaryKeySelective(stu);
//            result.setLockTimes("0");
//        }

//        if(!DateTimeUtil.isNow(result.getCreattime())){
//            int time = Integer.parseInt(result.getLockTimes());
//            User stu = new User();
//            stu.setStuno(result.getStuno());
//            stu.setLockTimes(String.valueOf(time+1));
//            userMapper.updateByPrimaryKeySelective(stu);
//        }
        //int time = Integer.parseInt(result.getLockTimes());
//        if((StringUtils.equals(result.getLockTimes(),"5"))&&DateTimeUtil.judgmentDate(DateTimeUtil.dateToStr(result.getLockDate()),DateTimeUtil.dateToStr(new Date()))){
//            return ServerResponse.createByErrorMessage("账号冻结中，请等待解锁");
//        }
//        if((StringUtils.equals(result.getLockTimes(),"5"))&&!DateTimeUtil.judgmentDate(DateTimeUtil.dateToStr(result.getLockDate()),DateTimeUtil.dateToStr(new Date()))){
//            time=0; //解锁后初始化为0
//        }


        //todo 密码登陆MD5
        String md5Password = MD5Util.MD5EncodeUtf8(stupassword);

        User user = userMapper.selectLogin(stuid,md5Password);

        if((StringUtils.equals(result.getLockTimes(),"5"))&& DateTimeUtil.judgmentDate(DateTimeUtil.dateToStr(result.getLockDate()), DateTimeUtil.dateToStr(new Date()))){
            return ServerResponse.createByErrorMessage("账号冻结中，请等待解锁");
        }

        if (user == null){
            //上面已经判断过用户存在了，这里查不到说明密码错误


            if(StringUtils.equals(result.getLockTimes(),"5")){
                result.setLockTimes("0");
            }

            int time = Integer.parseInt(result.getLockTimes().trim());

            User stu = new User();
            stu.setStuno(result.getStuno());
            stu.setLockTimes(String.valueOf(time+1));
            stu.setCreattime(new Date());
            if(StringUtils.equals("5",stu.getLockTimes())) {
                stu.setLockDate(new Date());
                userMapper.updateByPrimaryKeySelective(stu);
                return ServerResponse.createByErrorMessage("密码错误,已经输入错五次，账号冻结24小时");
            }
            userMapper.updateByPrimaryKeySelective(stu);
            return ServerResponse.createByErrorMessage("密码错误,你还有"+(5-time-1)+"次机会");
        }

        user.setStupassword(StringUtils.EMPTY);
        user.setLockTimes("0");
        user.setCreattime(new Date());

        User stu = new User();
        stu.setStuno(user.getStuno());
        stu.setLockTimes(String.valueOf("0"));
        stu.setCreattime(new Date());
        userMapper.updateByPrimaryKeySelective(stu);

        UserVo userVo = new UserVo();
        userVo = assembleUserVo(user);

        GroupUser groupUser = groupUserMapper.selectByUserNokey(user.getStuno());
        Group group = groupMapper.selectByPrimaryKey(groupUser.getGroupno());

        userVo.setGroupno(groupUser.getGroupno());
        userVo.setGroupname(group.getGroupname());

        return  ServerResponse.createBySuccess("登陆成功",userVo);
    }

    private UserVo assembleUserVo(User user){

        UserVo userVo = new UserVo();
        userVo.setStuno(user.getStuno());
        userVo.setStuid(user.getStuid());
        userVo.setProfession(user.getProfession());
        userVo.setStubirth(DateTimeUtil.dateToStr(user.getStubirth(),"yyyy-MM-dd"));
        userVo.setCreattime(DateTimeUtil.dateToStr(user.getCreattime()));
        userVo.setLockDate(DateTimeUtil.dateToStr(user.getLockDate()));
        userVo.setLockTimes(user.getLockTimes());
        userVo.setStatus(user.getStatus());
        userVo.setStuclass(user.getStuclass());
        userVo.setStucontent(user.getStucontent());
        userVo.setStuemail(user.getStuemail());
        userVo.setStuimgid(user.getStuimgid());
        userVo.setStuinstitute(user.getStuinstitute());
        userVo.setStusex(user.getStusex());
        userVo.setStupassword(user.getStupassword());
        userVo.setStuname(user.getStuname());

        return userVo;
    }

    //验证邮箱
    public boolean checkEmail(String email){

        Pattern pattern = Pattern.compile("^\\w+([-.]\\w+)*@\\w+([-]\\w+)*\\.(\\w+([-]\\w+)*\\.)*[a-z]{2,3}$");
        Matcher matcher = pattern.matcher(email);
        if (matcher.matches()){
            return true;
        }
        return false;
    }
    //验证电话
    public boolean checkPhone(String phone){
        Pattern pattern = Pattern.compile("^[1][3,4,5,7,8][0-9]{9}$");
        Matcher matcher = pattern.matcher(phone);

        if (matcher.matches()){
            return true;
        }
        return false;
    }



    public ServerResponse<String> register(User user){

        if(StringUtils.isBlank(user.getStuid())||StringUtils.isBlank(user.getStupassword())){
            return ServerResponse.createByErrorMessage("输入不能为空");
        }
        //检查除了学号和密码外其他输入想法为空，和检查邮箱，学号是否存在
        ServerResponse<String> r = this.checkIputeBlank(user);
        if(r != null){
            return r;
        }

        //检查学号是否已经存在
        //为了代码的复用性，把注释代码改了下
        ServerResponse validResponse = this.checkValid(user.getStuid(), Const.STUID);
        if(!validResponse.isSuccess()){
            return validResponse;
        }

        //检查邮箱是否已经存在
        validResponse = this.checkValid(user.getStuemail(), Const.EMAIL);
        if(!validResponse.isSuccess()){
            return validResponse;
        }

        //MD5加密
        user.setStupassword(MD5Util.MD5EncodeUtf8(user.getStupassword()));
        user.setLockTimes("0");
        user.setCreattime(new Date());
        user.setLockDate(new Date());
        user.setStatus(0);


        int resultCount = userMapper.insertSelective(user);
        User u = userMapper.checkStuId(user.getStuid());
        GroupUser groupUser = new GroupUser();
        groupUser.setstuno(u.getStuno());
        groupUser.setGroupno(Const.Role.ROLE_CUSTOMER);
        groupUser.setCreattime(new Date());
        int resultCount1 = groupUserMapper.insertSelective(groupUser);

        if(resultCount == 0&&resultCount1 == 0&&u==null){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return  ServerResponse.createByErrorMessage("注册失败");
        }
        return ServerResponse.createBySuccessMessage("注册成功");

    }

    /**
     * 检查用户输入信息，除了学号，密码为空不检查
     * @param user
     * @return
     */
    public ServerResponse checkIputeBlank(User user){
        if(StringUtils.isBlank(user.getStuname())
                ||StringUtils.isBlank(user.getStucontent())
                ||StringUtils.isBlank(user.getProfession())
                ||StringUtils.isBlank(user.getStuclass())
                ||StringUtils.isBlank(user.getStuinstitute())
                ||StringUtils.isBlank(user.getStuemail())
                ||StringUtils.isBlank(user.getStusex())
                || (user.getStubirth()==null)){
            return ServerResponse.createByErrorMessage("输入不能为空");
        }
//        if(DateTimeUtil.checkDate(DateTimeUtil.dateToStr(user.getStubirth(),"yyyy-MM-dd"),"yyyy-MM-dd")){
//            return ServerResponse.createByErrorMessage("生日格式错误");
//        }

        if(!this.checkEmail(user.getStuemail())){
            return ServerResponse.createByErrorMessage("email格式错误");
        }
        if(!this.checkPhone(user.getStucontent())){
            return ServerResponse.createByErrorMessage("电话格式错误");
        }
        if(!(StringUtils.equals(user.getStusex(),"男")||StringUtils.equals(user.getStusex(),"女"))){
            return ServerResponse.createByErrorMessage("性别格式不对");
        }

//        int resultCount = userMapper.checkUsername(user.getUsername());
//        if (resultCount > 0){
//            return ServerResponse.createByErrorMessage("用户名已存在");
//        }

//        //检查学号是否已经存在
//        //为了代码的复用性，把注释代码改了下
//        ServerResponse validResponse = this.checkValid(user.getStuid(), Const.STUID);
//        if(!validResponse.isSuccess()){
//            return validResponse;
//        }

//        resultCount = userMapper.checkEmail(user.getEmail());
//        if (resultCount > 0){
//            return ServerResponse.createByErrorMessage("email已存在");
//        }
//        //检查邮箱是否已经存在
//        ServerResponse validResponse = this.checkValid(user.getStuemail(),Const.EMAIL);
//        if(!validResponse.isSuccess()){
//            return validResponse;
//        }
        return null;
    }

    public ServerResponse<String> checkValid(String str, String type){
        //isNotBlank(),""和"  "都表示false,判断是否不为空，isBlank()判断是否为空
        if(StringUtils.isNoneBlank(type)){
            //开始校验
            if(Const.STUID.equals(type)){
                int resultCount = userMapper.checkStuIdCount(str);
                if (resultCount > 0){
                    return ServerResponse.createByErrorMessage("学号已存在");
                }
            }
            if(Const.EMAIL.equals(type)){
                int resultCount = userMapper.checkEmail(str);
                if (resultCount > 0){
                    return ServerResponse.createByErrorMessage("email已存在");
                }
            }
        }else {
            return ServerResponse.createByErrorMessage("参数错误");
        }
        return ServerResponse.createBySuccessMessage("校验成功");
    }

//    public ServerResponse selectQuestion(String username){
//        ServerResponse vaildResponse = this.checkValid(username,Const.USERNAME);
//        if(vaildResponse.isSuccess()) {
//            //用户不存在
//            return ServerResponse.createByErrorMessage("用户不存在");
//        }
//        String question = userMapper.selectQuestionByUsername(username);
//        if(StringUtils.isNoneBlank(question)){
//            return ServerResponse.createBySuccess(question);
//        }
//        return ServerResponse.createByErrorMessage("找回密码的问题是空的");
//    }
//
//    public ServerResponse<String> checkAnswer(String username,String question,String answer){
//        int resultCount =userMapper.checkAnswer(username,question,answer);
//        if(resultCount>0){
//            //说明问题及问题答案是这个用户的，并且是正确的
//            String forgetToken = UUID.randomUUID().toString();
//            TokenCache.setKey(TokenCache.TOKEN_PREFIX+username,forgetToken);
//            return ServerResponse.createBySuccess(forgetToken);
//        }
//        return ServerResponse.createBySuccessMessage("问题的答案错误");
//    }
//
//    public ServerResponse<String> forgetResetPassword(String username,String passwordNew,String forgetToken){
//        if(StringUtils.isBlank(forgetToken)){
//            return ServerResponse.createByErrorMessage("参数错误，token需要传递");
//        }
//        ServerResponse vaildResponse = this.checkValid(username,Const.USERNAME);
//        if(vaildResponse.isSuccess()) {
//            //用户不存在
//            return ServerResponse.createByErrorMessage("用户不存在");
//        }
//        String token = TokenCache.getKey(TokenCache.TOKEN_PREFIX+username);
//        //对缓存的token进行判断
//        if(StringUtils.isBlank(token)){
//            return ServerResponse.createByErrorMessage("token无效或者过期");
//        }
//        //这里的equals比较安全，传入null直接返回false，不会空指针
//        if(StringUtils.equals(forgetToken,token)){
//            String md5Password = MD5Util.MD5EncodeUtf8(passwordNew);
//            int rowCount = userMapper.updatePasswordByUsername(username,md5Password);
//            if(rowCount>0){
//                return ServerResponse.createBySuccessMessage("修改密码成功");
//            }
//        }else {
//            return ServerResponse.createByErrorMessage("token错误，请重新获取重置密码的token");
//        }
//        return ServerResponse.createByErrorMessage("修改密码失败");
//    }

    public ServerResponse<String> resetPassword(String passwordOld, String passwordNew1, String passwordNew2 , UserVo userVo){
        //防止横向越权，要校验下这个用户的旧密码，一定要指定是这个用户，因为我们会查询一个count(1)，要大于0
        //如果不指定用户，别人不断地用这个接口是密码会很多机会count(1)>1的

        if(StringUtils.isBlank(passwordOld)){
            ServerResponse.createByErrorMessage("原密码输入不能为空");
        }
        if(StringUtils.isBlank(passwordNew1)){
            ServerResponse.createByErrorMessage("新密码输入不能为空");
        }
        if(StringUtils.isBlank(passwordNew2)){
            ServerResponse.createByErrorMessage("新密码输入不能为空");
        }

        int resultCount = userMapper.checkPassword(MD5Util.MD5EncodeUtf8(passwordOld),userVo.getStuno());
        if(resultCount==0){
            return ServerResponse.createByErrorMessage("旧密码错误");
        }

        if(!StringUtils.equals(passwordNew1,passwordNew2)){
            return ServerResponse.createByErrorMessage("两次输入的新密码不一致");
        }

        User user = new User();
        user.setStuno(userVo.getStuno());
        user.setStupassword(MD5Util.MD5EncodeUtf8(passwordNew1));


        int updateCount = userMapper.updateByPrimaryKeySelective(user);
        if(updateCount>0){
            return ServerResponse.createBySuccessMessage("密码更新成功");
        }
        return ServerResponse.createByErrorMessage("密码更新失败");
    }

    public ServerResponse<UserVo> updateInformation(User user){
        //username是不能被更新的
        //email也要进行校验，校验新的email是不是已存在，如果存在相同的，不能是当前用户的email

        //检查除了学号和密码外其他输入想法为空，和检查邮箱，学号是否存在
        ServerResponse r = this.checkIputeBlank(user);
        if(r != null){
            return r;
        }

        int resultCount = userMapper.checkEmailByUserId(user.getStuemail(),user.getStuno());
        if(resultCount>0){
            return ServerResponse.createByErrorMessage("email已存在，请更换email再尝试更新");
        }

        User updateUser = new User();
        updateUser.setStuno(user.getStuno());
        updateUser.setStuname(user.getStuname());
        updateUser.setStuemail(user.getStuemail());
        updateUser.setStucontent(user.getStucontent());
        updateUser.setStusex(user.getStusex());
        updateUser.setStubirth(user.getStubirth());
        updateUser.setProfession(user.getProfession());
        updateUser.setStuinstitute(user.getStuinstitute());
        updateUser.setStuclass(user.getStuclass());
        updateUser.setCreattime(new Date());

        int updateCount = userMapper.updateByPrimaryKeySelective(updateUser);
        if(updateCount>0){

            return  ServerResponse.createBySuccess("更新个人信息成功",assembleUserVo(updateUser));
        }
        return  ServerResponse.createByErrorMessage("更新个人信息失败");
    }

    public ServerResponse<UserVo> getInformation(Integer stuNo){
        User user = userMapper.selectByPrimaryKey(stuNo);
        if(user == null){
            return ServerResponse.createByErrorMessage("找不到当前用户");
        }
        //把密码置空
        user.setStupassword(StringUtils.EMPTY);
        UserVo userVo = new UserVo();
        userVo = assembleUserVo(user);
        GroupUser groupUser = groupUserMapper.selectByUserNokey(user.getStuno());
        Group group = groupMapper.selectByPrimaryKey(groupUser.getGroupno());

        userVo.setGroupno(groupUser.getGroupno());
        userVo.setGroupname(group.getGroupname());
        return ServerResponse.createBySuccess(userVo);
    }

    //backend

    /**
     * 校验是否是管理员且验证session信息和数据库是否一致
     * @param userVo
     * @return
     */
    public ServerResponse<Integer> checkAdminRole(UserVo userVo){
        if(userVo != null && userVo.getGroupno().intValue() >= Const.Role.ROLE_ADMIN&&
                groupUserMapper.selectByUserNokey(userVo.getStuno()).getGroupno()==userVo.getGroupno()){
            return ServerResponse.createBySuccess(userVo.getGroupno());
        }
        return ServerResponse.createByError();
    }

    /**
     * 校验是否是超级管理员
     * @param userVo
     * @return
     */
    public ServerResponse checkSAdminRole(UserVo userVo){
        if(userVo != null && userVo.getGroupno().intValue() == Const.Role.ROLE_SADMIN&&
                groupUserMapper.selectByUserNokey(userVo.getStuno()).getGroupno()>= Const.Role.ROLE_SADMIN){
            return ServerResponse.createBySuccess();
        }
        return ServerResponse.createByError();
    }

    /**
     * 检查该管理员是否有这个权限
     * @param userVo
     * @return
     */
    public ServerResponse checkPrivilege(UserVo userVo, String url){
//        String url = request.getRequestURL().toString();
        List<GroupPrivilege> groupPrivilegeList =  groupPrivilegeMapper.selectByGroup(userVo.getGroupno());
        List<Privilege> privilegeList =  Lists.newArrayList();
        for(GroupPrivilege groupPrivilege : groupPrivilegeList){
            privilegeList.add(privilegeMapper.selectByPrimaryKey(groupPrivilege.getPermno()));
        }
        boolean haspermission = false;
        for (Privilege privilege : privilegeList) {
            if (url.contains(privilege.getPermission())) {
                haspermission = true;
                break;
            }
        }

        if(haspermission||userVo.getGroupno().intValue()== Const.Role.ROLE_SADMIN){
           return ServerResponse.createBySuccess();
        }
        return ServerResponse.createByError();
    }

    public ServerResponse resetAdminPassword(List<Integer> stunoList, String password){


        for(Integer stuno:stunoList){
            User user = new User();
            user.setStuno(stuno);
            user.setStupassword(MD5Util.MD5EncodeUtf8(password));

            int updateCount = userMapper.updateByPrimaryKeySelective(user);
            if(updateCount<=0){
                return ServerResponse.createByErrorMessage("密码更新失败");
            }
        }

        return ServerResponse.createBySuccessMessage("密码更新成功");

    }

    public ServerResponse adminLockUser(List<Integer> stunoList){

        for(Integer stuno:stunoList) {
            User user = new User();
            user.setStuno(stuno);
            user.setStatus(1);

            int updateCount = userMapper.updateByPrimaryKeySelective(user);
            if (updateCount <= 0) {
                return ServerResponse.createByErrorMessage("锁定用户失败");
            }
        }

        return ServerResponse.createBySuccessMessage("锁定用户成功");

    }


    public ServerResponse adminDeblockUser(List<Integer> stunoList){

        for(Integer stuno:stunoList){
            User user = new User();
            user.setStuno(stuno);
            user.setLockTimes("0");
            user.setStatus(0);

            int updateCount = userMapper.updateByPrimaryKeySelective(user);
            if(updateCount<=0){
                return ServerResponse.createByErrorMessage("解锁用户失败");
            }
        }
        return ServerResponse.createBySuccessMessage("解锁用户成功");
    }


    public ServerResponse deleteUser(List<Integer> stunoList){

        for(Integer stuno:stunoList) {
            GroupUser groupUser = groupUserMapper.selectByUserNokey(stuno);
            if(groupUser.getGrostuno()!=1){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return ServerResponse.createByErrorMessage("选项中有管理员，不能删除");
            }
            //软删除，所以重写
//            int updateCount = userMapper.deleteByPrimaryKey(stuno);
//            int updateCount2 =  projectDetailsUserMapper.deleteByStuNo(stuno);
//
//            ProjectDetailsUser projectDetailsUser = projectDetailsUserMapper.selectByStuno(stuno);
//
//            int updateCount3 = projectDetailsMapper.deleteByPrimaryKey(projectDetailsUser.getProjectno());
//            if (updateCount <= 0 ||updateCount2<=0 || updateCount3<=0) {
//                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//                return ServerResponse.createByErrorMessage("删除用户失败");
//            }


            int updateCount = userMapper.deleteByPrimaryKey(stuno);
            if (updateCount <= 0) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return ServerResponse.createByErrorMessage("删除用户失败");
            }

        }
        return ServerResponse.createBySuccessMessage("删除用户成功");
    }

    public ServerResponse<List<ListUserVo>> listUser(){

        List<User> userList = userMapper.selectListUser();
        int Count = 0;
        if(CollectionUtils.isEmpty(userList)){
            logger.info("未找到用户");
        }

        List<ListUserVo> listUserVos = Lists.newArrayList();
        for(User userItem : userList){
            Count++;
            ListUserVo listUserVo = assembleUserListVo(userItem);
            listUserVos.add(listUserVo);
        }

        return ServerResponse.createBySuccess(listUserVos);
    }

//    public ServerResponse<PageInfo> listUserPage(int pageNum,int pageSize){
//
//        //startPage--start
//        //填充自己的sql查询逻辑
//        //pageHelper-收尾
//        PageHelper.startPage(pageNum,pageSize);
//        List<User> userList = userMapper.selectListUser();
//
//        if(CollectionUtils.isEmpty(userList)){
//            logger.info("未找到用户");
//        }
//
//        List<ListUserVo> listUserVos = Lists.newArrayList();
//        for(User userItem : userList){
//
//            ListUserVo listUserVo = assembleUserListVo(userItem);
//            listUserVos.add(listUserVo);
//        }
//        PageInfo pageResult = new PageInfo(userList);
//        pageResult.setList(listUserVos);
//
//
//
//        return ServerResponse.createBySuccess("第"+pageNum+"页，共"+pageResult.getPages()+"页，"+pageResult.getTotal()+"条数据",pageResult);
//    }

    public ServerResponse<PageInfo> searchUser(String name, Integer groupno,int pageNum, int pageSize, int time_sort){
        PageHelper.startPage(pageNum,pageSize);

        List<User> userList;

        if(StringUtils.isNotBlank(name)){
            name = new StringBuilder().append("%").append(name).append("%").toString();
            if(time_sort==0){
                userList = userMapper.selectSearchUser(name);
            }else {
                userList = userMapper.selectSearchUserTimeSort(name);
            }

        }else {
            name=null;
            if(time_sort==0){
                userList = userMapper.selectListUser();  //所有用户的接口
            }else {
                userList = userMapper.selectListUserTimeSort();  //所有用户的接口
            }

        }



        if(CollectionUtils.isEmpty(userList)){
            logger.info("未找到用户");
        }

        List<ListUserVo> listUserVos = Lists.newArrayList();
        for(User userItem : userList){
            ListUserVo listUserVo = assembleUserListVo(userItem);
            listUserVos.add(listUserVo);
        }

        PageInfo pageResult = new PageInfo(userList);
        pageResult.setList(listUserVos);


        //筛选分组
        if(groupno!=null){


            List<User> userList2=new ArrayList<>();

            if(StringUtils.isNotBlank(name)){
                name = new StringBuilder().append("%").append(name).append("%").toString();
                if(time_sort==0){
                    userList2 = userMapper.selectSearchUser(name);
                }else {
                    userList2 = userMapper.selectSearchUserTimeSort(name);
                }

            }else {
                name=null;
                if(time_sort==0){
                    userList2 = userMapper.selectListUser();  //所有用户的接口
                }else {
                    userList2 = userMapper.selectListUserTimeSort();  //所有用户的接口
                }

            }
            System.out.println(userList2.size());



            if(CollectionUtils.isEmpty(userList2)){
                logger.info("未找到用户");
            }

            List<ListUserVo> listUserVos2 = Lists.newArrayList();
            for(User userItem : userList2){
                ListUserVo listUserVo = assembleUserListVo(userItem);
                listUserVos2.add(listUserVo);
            }




            List<ListUserVo> users = new ArrayList<>();
            for(ListUserVo item:listUserVos2){
                GroupUser groupUser = groupUserMapper.selectByUserNokey(item.getStuno());
                if(groupUser==null){
                    continue;
                }
                if(groupUser.getGroupno()==null){
                    continue;
                }
                if(groupUser.getGroupno().equals(groupno)){
                    users.add(item);
                }
            }
            listUserVos2=users;

            int pages = (int)(listUserVos2.size()/pageSize);
            if(listUserVos2.size()%pageSize!=0){
                pages+=1;
            }
            if(pageNum>pages){
                pageResult.setSize(0);
                pageResult.setTotal(listUserVos2.size());
                pageResult.setPages(pages);
                pageResult.setLastPage(pages);
                pageResult.setList(new ArrayList());
                return ServerResponse.createBySuccess("第"+pageNum+"页，共"+pageResult.getPages()+"页，"+pageResult.getTotal()+"条数据",pageResult);
            }
            if(listUserVos2.size()%pageSize!=0){


                if(pages==pageNum){
                    pageResult.setTotal(listUserVos2.size());
                    pageResult.setPages(pages);
                    pageResult.setLastPage(pages);
                    pageResult.setList(listUserVos2.subList((pageNum-1)*pageSize,listUserVos2.size()));
                    pageResult.setSize(pageResult.getList().size());
                    return ServerResponse.createBySuccess("第"+pageNum+"页，共"+pageResult.getPages()+"页，"+pageResult.getTotal()+"条数据",pageResult);
                }else {
                    pageResult.setTotal(listUserVos2.size());
                    pageResult.setPages(pages);
                    pageResult.setLastPage(pages);
                    pageResult.setList(listUserVos2.subList((pageNum-1)*pageSize,pageNum*pageSize));
                    pageResult.setSize(pageResult.getList().size());
                    return ServerResponse.createBySuccess("第"+pageNum+"页，共"+pageResult.getPages()+"页，"+pageResult.getTotal()+"条数据",pageResult);
                }
            } else {
                pageResult.setTotal(listUserVos2.size());
                pageResult.setPages(pages);
                pageResult.setLastPage(pages);
                pageResult.setList(listUserVos2.subList((pageNum-1)*pageSize,pageNum*pageSize));
                pageResult.setSize(pageResult.getList().size());
                return ServerResponse.createBySuccess("第"+pageNum+"页，共"+pageResult.getPages()+"页，"+pageResult.getTotal()+"条数据",pageResult);
            }



        }




        return ServerResponse.createBySuccess("第"+pageNum+"页，共"+pageResult.getPages()+"页，"+pageResult.getTotal()+"条数据",pageResult);
    }


//    public  ServerResponse exportBusInfo(List<Integer> stunoList , HttpServletRequest request, HttpServletResponse response) throws IOException {
//
//        ResponseEntity<byte[]> rusult = null;
//
//        String path = request.getSession().getServletContext().getRealPath("/") + File.separator+"WEB-INF"+File.separator+"file";
//        //创建该文件对象
//        File file_dir = new File(path);
//        //如果保存文件的地址不存在，就先创建目录
//        if(!file_dir.exists()){
//            file_dir.mkdir();
//        }
//
//        List<User> userList = userMapper.selectByIdUser(stunoList);
//
//        if(CollectionUtils.isEmpty(userList)){
//            logger.info("未找到用户");
//        }
//
//        List<User> exList = new ArrayList<>();
//        ExportExcel<User> extExcel = new ExportExcel<>();
//        User u = null;
//        //表头
//        String[] headers = {"1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1"};
//        //sheet名称
//        String sheetname = "用户信息";
//        //路径+文件名
//        String fileName = "用户信息" + System.currentTimeMillis() + ".xls";
//
//        //创建该文件对象
//        File file = new File(path,fileName);
//
//        FileOutputStream out = null;
//
//        try{
//            out = new FileOutputStream(file);
//
//
//
//            for(User useritem : userList){
//                //如果不是整个user写入需要一个bean装换对象
//
//                exList.add(useritem);
//            }
//            //生产excel文件
//            extExcel.exportExcelCar(headers,sheetname,exList,out);
//
//            rusult = extExcel.download(path,fileName,request,response);
//
//
//        }catch (Exception e){
//            return ServerResponse.createByError();
//        }finally {
//            out.close();
//            File file1 = new File(path,fileName);
//            file1.delete();
//
//        }
//        if(rusult != null)
//            return ServerResponse.createBySuccess(rusult);
//        else
//            return ServerResponse.createByError();
//   }

    public ExportExcelVo<byte[]> exportBusInfo(List<Integer> stunoList, HttpServletRequest request, HttpServletResponse response) throws Exception {

        ExportExcelVo<byte[]> exportExcelVo = null;

        ServerResponse<byte[]> rusult = null;

        String path = request.getSession().getServletContext().getRealPath("/") + File.separator + "WEB-INF" + File.separator + "file";
        //创建该文件对象
        File file_dir = new File(path);
        //如果保存文件的地址不存在，就先创建目录
        if (!file_dir.exists()) {
            file_dir.mkdir();
        }

        List<User> userList;

        if(CollectionUtils.isEmpty(stunoList)||stunoList==null){
            userList = userMapper.selectAllUser();
        }else {
            userList = userMapper.selectByIdUser(stunoList);
        }


        if (CollectionUtils.isEmpty(userList)) {
            logger.info("未找到用户");
        }

        List<ExcelFileVo> exList = new ArrayList<>();
        ExportExcel<ExcelFileVo> extExcel = new ExportExcel<>();
        User u = null;
        //表头
        String[] headers = {"用户ID(学号)", "用户名", "电话号码", "学院", "班级", "性别", "出生日期", "邮箱"};
        //sheet名称
        String sheetname = "用户信息";
        //路径+文件名
        String fileName = "用户信息" + System.currentTimeMillis() + ".xls";

        //创建该文件对象
        File file = new File(path, fileName);

        FileOutputStream out = null;

        try {
            out = new FileOutputStream(file);


            for (User useritem : userList) {
                //如果不是整个user写入需要一个bean装换对象
                ExcelFileVo excelFileVo = new ExcelFileVo();
                excelFileVo.setStuid(useritem.getStuid());
                excelFileVo.setStuname(useritem.getStuname());
                excelFileVo.setStucontent(useritem.getStucontent());
                excelFileVo.setStuinstitute(useritem.getStuinstitute());
                excelFileVo.setStuclass(useritem.getStuclass());
                excelFileVo.setStusex(useritem.getStusex());
                excelFileVo.setStubirth(useritem.getStubirth());
                excelFileVo.setStuemail(useritem.getStuemail());
                exList.add(excelFileVo);
            }
            //生产excel文件
            extExcel.exportExcelCar(headers, sheetname, exList, out);

            rusult = extExcel.download(path, fileName, request, response);
            System.out.println("rusult="+rusult.getData());


        } catch (Exception e) {
            exportExcelVo.setFileName(null);
            exportExcelVo.setServerResponse(ServerResponse.createByErrorMessage("异常退出"));
            return exportExcelVo;
        } finally {
            out.close();
            File file1 = new File(path, fileName);
            file1.delete();

        }
        if (rusult != null){
//            Gson gson = new Gson();
//            String r;
//            r = gson.toJson(ServerResponse.createBySuccess(rusult));
            fileName = ExportExcel.getFilename(request,fileName);
            exportExcelVo = new ExportExcelVo<>();
            exportExcelVo.setFileName(fileName);
            exportExcelVo.setServerResponse(rusult);
            return exportExcelVo;
        }
        else
        {
            exportExcelVo.setFileName(null);
            exportExcelVo.setServerResponse(ServerResponse.createByErrorMessage("没有文件导出"));
            return exportExcelVo;
        }
    }



    private ListUserVo assembleUserListVo(User user){
        ListUserVo listUserVo = new ListUserVo();
        listUserVo.setStuno(user.getStuno());
        listUserVo.setStuid(user.getStuid());
        listUserVo.setProfession(user.getProfession());
        listUserVo.setStatus(user.getStatus());
        listUserVo.setStubirth(DateTimeUtil.dateToStr(user.getStubirth(),"yyyy-MM-dd"));
        listUserVo.setStuemail(user.getStuemail());
        listUserVo.setStuinstitute(user.getStuinstitute());
        listUserVo.setStucontent(user.getStucontent());
        listUserVo.setStuclass(user.getStuclass());
        listUserVo.setStuname(user.getStuname());
        listUserVo.setStusex(user.getStusex());
        return listUserVo;
    }


    public ServerResponse updateManageInformation(User user){
        //username是不能被更新的
        //email也要进行校验，校验新的email是不是已存在，如果存在相同的，不能是当前用户的email

        //检查除了学号和密码外其他输入想法为空，和检查邮箱，学号是否存在
        ServerResponse r = this.checkIputeBlank(user);
        if(r != null){
            return r;
        }

        int resultCount = userMapper.checkEmailByUserId(user.getStuemail(),user.getStuno());
        if(resultCount>0){
            return ServerResponse.createByErrorMessage("email已存在，请更换email再尝试更新");
        }


        int updateCount = userMapper.updateByPrimaryKeySelective(user);
        if(updateCount>0){

            return  ServerResponse.createBySuccessMessage("更新个人信息成功");
        }
        return  ServerResponse.createByErrorMessage("更新个人信息失败");
    }


    public ServerResponse getPassword(HttpServletRequest request,String stuid){

        User user = userMapper.checkStuId(stuid);

        HashMap<String, String> map = SendMsgUtil.getMessageStatus(user.getStucontent().trim()); //调用发送短信接口

        String result = map.get("result");//获取到result值
        if (result.trim().equals("1")) {//如果为1，表示成功发送

            String code = map.get("code");//获取发送的验证码内容
            HttpSession session = request.getSession(); //设置session
            session.setAttribute("code", code);//将短信验证码放到session中保存
            session.setMaxInactiveInterval(60 * 5);//保存时间 暂时设定为5分钟

            System.out.println(code);
            return ServerResponse.createBySuccessMessage("发送信息成功");

        } else {
            //短信发送失败
            return ServerResponse.createByErrorMessage("发送信息失败");
        }

    }



    public ServerResponse AddAdmin(User userold){
        if(StringUtils.isBlank(userold.getStuid())){
            return ServerResponse.createByErrorMessage("管理员账号名不能为空");
        }

        //检查学号是否已经存在
        //为了代码的复用性，把注释代码改了下
        ServerResponse validResponse = this.checkValid(userold.getStuid(), Const.STUID);
        if(!validResponse.isSuccess()){
            return validResponse;
        }

        //MD5加密
        User user = new User();
        user.setStuname(userold.getStuid());
        user.setStuid(userold.getStuid());
        user.setStusex("男");
        user.setStupassword(MD5Util.MD5EncodeUtf8(userold.getStuid()));
        user.setLockTimes("0");
        user.setCreattime(new Date());
        user.setLockDate(new Date());
        user.setStatus(0);


        int resultCount = userMapper.insertSelective(user);
        User u = userMapper.checkStuId(user.getStuid());
        if(u==null){
            return  ServerResponse.createByErrorMessage("添加失败");
        }
        GroupUser groupUser = new GroupUser();
        groupUser.setstuno(u.getStuno());
        groupUser.setGroupno(Const.Role.ROLE_SADMIN);
        groupUser.setCreattime(new Date());
        int resultCount1 = groupUserMapper.insertSelective(groupUser);

        if(resultCount == 0||resultCount1 == 0||u==null){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return  ServerResponse.createByErrorMessage("添加失败");
        }
        return ServerResponse.createBySuccessMessage("添加成功");
    }

}
